package leetcode.to300;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @ClassName T0002
 * @Description 两数相加
 * @Author Fanxc
 * @DATE 2021/1/22 14:03
 * @Version 1.0
 */
public class T0002 {
    class ListNode{
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
            this.next=null;
        }
    }
    //使用两个栈，来进行加法的运算
    class Solution{
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            Deque<Integer> stack1=new LinkedList<>();
            Deque<Integer> stack2=new LinkedList<>();
            while (l1!=null){
                stack1.push(l1.val);
                l1=l1.next;
            }
            while (l2!=null){
                stack2.push(l2.val);
                l2=l2.next;
            }
            int carry=0;
            ListNode ans=null;
            while (!stack1.isEmpty() || !stack2.isEmpty() ||carry!=0){
                int a = stack1.isEmpty() ? 0 : stack1.pop();
                int b = stack2.isEmpty() ? 0 : stack2.pop();
                int cur =a+b+carry;
                carry=cur/10;
                cur%=10;
                //新建一个链表
                ListNode curnode=new ListNode(cur);
                curnode.next=ans;
                ans=curnode;

            }
            return ans;
        }

    }
}
